<?php
/**
 * (jobs)
 */
namespace App\Jobs\OverSeasIn;

use App\Models\OverSeasBa\RemovaleInventoryFNSku;
use App\Models\OverSeasBa\Warehouse;
use App\Models\OverSeasIn\RemovaleOrderDetail;
use App\Models\OverSeasIn\RemovalePlan;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class RemovaleOrderDetailUpload implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $orderIds;

    /**
     * RemovaleOrderDetailUpload constructor.
     * @param $orderIds
     */
    public function __construct($orderIds)
    {
        $this->orderIds = $orderIds;
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle()
    {
        $this->exeFillData($this->orderIds);
    }

    private function exeFillData($orderIds){
        $rods = RemovaleOrderDetail::query()
            ->whereIn('order_id',$orderIds)
            ->get();
        $warehouseIDs = [];
        $warehouses = [];
        foreach ($rods as $rod){
            if(!array_key_exists($rod->order_id,$warehouseIDs)){
                $warehouseIDs[$rod->order_id] = RemovalePlan::query()
                    ->where('order_id' , $rod->order_id)
                    ->value('warehouse_id');
            }
            $warehouseId = $warehouseIDs[$rod->order_id];
            if(!$warehouseId)continue;
            if(!array_key_exists($warehouseId,$warehouses)){
                $warehouses[$warehouseId] = Warehouse::getWarehouseById($warehouseId);
            }
            $warehouse = $warehouses[$warehouseId];
            if(!$warehouse)continue;
            if($rod->warehouse_id > 0){
                $inventoryOld = RemovaleInventoryFNSku::query()
                    ->where('account_id' , $rod->account_id)
                    ->where('warehouse_id' , $rod->warehouse_id)
                    ->where('fnsku' , $rod->fnsku)
                    ->first();
                if($inventoryOld){
                    $inventoryOld->transit -= min($inventoryOld->transit,$rod->shipped_quantity);
                    $inventoryOld->save();
                }
            }
            $rod->warehouse_id = $warehouseId;
            $rod->area_id = $warehouse->area_id;
            $rod->country_id = $warehouse->country_id;
            $rod->save();
            $inventory = RemovaleInventoryFNSku::query()
                ->firstOrNew(
                    [
                        'account_id' => $rod->account_id,
                        'warehouse_id' => $rod->warehouse_id,
                        'fnsku' => $rod->fnsku,
                    ],[
                        'psku_id' => $rod->psku_id,
                    ]
                );
            $inventory->transit += $rod->shipped_quantity;
            $inventory->save();
        }
    }
}
